/*
 * standardrequestmanager.h
 *
 *  Created on: Sep 11, 2011
 *      Author: anonovermind <anonovermind@gmail.com>
 */

#ifndef STANDARDREQUESTMANAGER_H_
#define STANDARDREQUESTMANAGER_H_

#include "requestmanager.h"
#include <queue>
#include <list>
#include <chrono>

namespace Wishmaster2
{
namespace Network
{

class StandardRequestManager: public Wishmaster2::Network::RequestManager
{
public:
	StandardRequestManager();
	virtual ~StandardRequestManager();

	virtual void registerMedium(NetworkMedium* medium);
	virtual void unregisterMedium(const std::string& protocol);

	virtual RequestPtr createRequest(const Url& url);
	virtual bool enqueueRequest(const RequestPtr& request);
	virtual void acknowledgeRequest(int id);
	virtual void setQueueDepth(int depth);
	virtual RequestPtr request(int id) const;

	virtual void saveSettings(const std::string& path);
	virtual void loadSettings(const std::string& path);

protected:
	void requestFinished(int id);
	void requestProgress(int id, int current, int total);
	void requestError(int id, const std::string message);

	void moveFinishedRequestToDone(int id);
	void enqueueNextRequest();
	void removeStaleDoneRequests();

private:
	std::list<RequestPtr> m_current;
	struct DoneRequest
	{
		std::chrono::time_point<std::chrono::system_clock> doneTime;
		RequestPtr request;
	};

	std::list<DoneRequest> m_done;
	std::list<RequestPtr> m_pending;
	unsigned int m_currentQueueMaxSize;

	std::list<NetworkMedium*> m_media;

	int m_currentId;
};

} /* namespace Network */
} /* namespace Wishmaster2 */
#endif /* STANDARDREQUESTMANAGER_H_ */
